<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
                >新增角色</el-button
              >
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="hAssign(scope.row.id)"
                    >分配权限</el-button
                  >
                  <el-button
                    size="small"
                    type="primary"
                    @click="hEdit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="hDel(scope.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                @current-change="hCurrentChange"
                @size-change="hSizeChange"
                :total="total"
                :page-size="pagesize"
                :page-sizes="[2, 4, 6, 8]"
                layout=" sizes,prev,pager,next"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息"></el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑' : '添加'"
        @close="hClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
      >
        <el-form
          ref="roleForm"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit"
              >确定</el-button
            >
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog
        :title="1 ? '编辑' : '添加'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialogPermission"
      >
        <AssignPermission ref="refperm" :role-id="roleId" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, delRoles, addRole, editRole } from "@/api/setting";
import AssignPermission from "./assignPermission.vue";
export default {
  data() {
    return {
      showDialog: false, //默认不显示弹窗
      isEdit: false,
      showDialogPermission: false, //分配权限
      roleId: "",
      roleForm: {
        name: "",
        description: "",
      },
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "描述不能为空", trigger: "blur" },
        ],
      },

      pagesize: 2,
      page: 1,

      total: 5, //总条数
      list: [],
    };
  },
  created() {
    this.loadRoles();
  },
  // 注册组件
  components: {
    AssignPermission,
  },
  methods: {
    // 分配权限成功
    hSuccess() {
      this.showDialogPermission = false;
      this.$message.success("成功");
    },
    // 点击分配权限
    hAssign(id) {
      // 显示弹框
      this.showDialogPermission = true;
      // 保存id
      this.roleId = id;
      // 解决只执行一次的问题
      this.$nextTick(() => {
        this.$refs.refperm.loadPermissionById();
      });
    },
    // 取消关闭编辑
    hClose() {
      this.$refs.roleForm.resetFields();
    },
    // 点击编辑
    hEdit(data) {
      this.isEdit = true;
      console.log(data);
      this.showDialog = true;
      // 数据回填
      this.roleForm = { ...data };
    },
    async doDel(id) {
      try {
        await delRoles(id);
        this.$message.success("删除成功");
        // 如果删除是最后一条数据,页码则要-1
        if (this.list.length === 1) {
          let page = this.page;
          page--;
          // 不能是0
          page = Math.max(1, page);
          this.page = page;
        }
        // 重发请求
        this.loadRoles();
      } catch (error) {
        console.log(error);
      }
    },
    // 删除
    hDel(id) {
      this.$confirm("确认删除吗?", "系统提示")
        .then(() => {
          this.doDel(id);
        })
        .catch(() => {});
    },
    // 更新页码
    hSizeChange(curPageSize) {
      console.log(curPageSize);
      // 更新页码
      this.pagesize = curPageSize;
      // 重发请求
      this.loadRoles();
    },
    hCurrentChange(curPage) {
      console.log(curPage);
      // 更新页码
      this.page = curPage;
      // 重发请求
      this.loadRoles();
    },
    async loadRoles() {
      try {
        const res = await getRoles({
          page: this.page,
          pagesize: this.pagesize,
        });
        console.log("res", res);
        this.total = res.data.total;
        this.list = res.data.rows;
      } catch (error) {
        this.$message.error(error);
      }
    },
    hAdd() {
      this.showDialog = true;
      this.isEdit = false;
    },
    hSubmit() {
      // 确认
      // 表单校验
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          // if (this.isEdit) {
          //   this.doEdit();
          // } else {
          //   this.doAdd();
          // }

          this.isEdit ? this.doEdit() : this.doAdd();
        }
      });
    },
    // 添加角色
    async doAdd() {
      try {
        // 添加
        await addRole(this.roleForm);
        // 重发请求
        // 添加完数据后要跳转到最后一页的交互
        // math.ceil(x) # 返回不小于x的最接近的整数

        this.page = Math.ceil((this.total + 1) / this.pagesize); //最后一页
        this.loadRoles();
        // 提示框
        this.$message.success("添加成功");
        // 关闭弹窗
        this.showDialog = false;
      } catch (err) {
        // 提示框
        this.$message.error("添加失败");
        console.log(err);
      }
    },
    async doEdit() {
      try {
        // 添加
        await editRole(this.roleForm);
        // 重发请求

        this.loadRoles();
        // 提示框
        this.$message.success("修改成功");
        // 关闭弹窗
        this.showDialog = false;
      } catch (err) {
        // 提示框
        this.$message.error("修改失败");
        console.log(err);
      }
    },
  },
};
</script>

